package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.callback.SendEmailCallback;
import com.cskaoyan.order.biz.callback.TransCallback;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {


    @Autowired
    SendEmailCallback sendEmailCallback;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;



    private final String ORDER_GLOBAL_ID_CACHE_KEY="ORDER_ID";
    private final String ORDER_ITEM_GLOBAL_ID_CACHE_KEY="ORDER_ITEM_ID";
    @Override
    public TransCallback getTransCallback() {
        return sendEmailCallback;
    }

    @Override
    public boolean isAsync() {

//
        return true;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context1) {
        System.out.println("初始化订单 生成订单!InitOrderHandler");
        String order_id = globalIdGeneratorUtil.getNextSeq(ORDER_GLOBAL_ID_CACHE_KEY, 1);
        System.out.println("初始化订单 生成订单 : order_id = " + order_id);
        CreateOrderContext context=(CreateOrderContext)context1;
        Order order = new Order();
        order.setUpdateTime(new Date());
        order.setCreateTime(new Date());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        order.setOrderId(order_id);
        order.setUserId(context.getUserId());
        order.setPayment(context.getOrderTotal());
        order.setBuyerNick(context.getUserName());
        orderMapper.insertSelective(order);

        List<CartProductDto> goods = context.getCartProductDtoList();
        List<Long> ids=new ArrayList<>();
        for (CartProductDto good : goods) {
            ids.add(good.getProductId());
            OrderItem orderItem = new OrderItem();
            String order_item_id = globalIdGeneratorUtil.getNextSeq(ORDER_ITEM_GLOBAL_ID_CACHE_KEY, 1);
//      TODO          orderItem.setId();
            orderItem.setId(order_item_id);

            orderItem.setItemId(good.getProductId());
            orderItem.setNum(Integer.parseInt(good.getProductNum() + ""));
//      TODO          orderItem.setOrderId( );
            orderItem.setOrderId(order_id);
            orderItem.setTitle(good.getProductName());
            orderItem.setPrice(good.getSalePrice());
//            double price = Double.parseDouble(good.getSalePrice() + "");
//            Double totalfee=good.getProductNum()*price ;
            BigDecimal total =
                    good.getSalePrice().multiply(new BigDecimal(good.getProductNum()));
            orderItem.setTotalFee(total);
            orderItem.setPicPath(good.getProductImg());
            orderItem.setStatus(1);

            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            orderItemMapper.insert(orderItem);
//             INSERT INTO tb_order_item  ( id,item_id,order_id,num,title,price,total_fee,pic_path,status,create_time,update_time ) VALUES( ?,?,?,?,?,?,?,?,?,?,? )
//### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '22042509032488798' for key 'PRIMARY'
//                orderItem.set
        }

        context.setOrderId(order_id);
        context.setBuyProductIds(ids);
//        ??????
        context.setUniqueKey(order_id);

        return true;
    }

}
